# -*- coding: utf-8 -*-
# @Time    : 2023/11/24 15:35
# @Author  : Jonny
# @File    : LuckDingtalkService.py
# @Describe: 钉钉逻辑服务层
import os
import logging
import time
import json

from LuckDingtalkApi import LuckDingtalkApi
from LuckDbHelperUtils import LuckSqliteHelperUtils
from LuckDingtalkConstant import LuckDingtalkConstant


class LuckDingtalkService(object):
    def __init__(self, config):
        self.config = config

    # 创建记录表
    def create_table(self):
        # 获取当前脚本的路径
        script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
        with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
            cursor.execute(
                '''create table luck_dingtalk (id text, check_time text, check_user text, check_environment text, check_item text, check_data text, check_state text, except_note text, handle_state text)''')
            cursor.execute(
                '''create table luck_dingtalk_error (id text, check_time text, check_user text, check_environment text, check_item text, except_note text)''')
        result = {
            "code": 1,
            "msg": "创建记录表成功"
        }
        return result

    # 删除记录表数据
    def delete_table(self):
        # 获取当前脚本的路径
        script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
        with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
            cursor.execute('delete from luck_dingtalk')
            cursor.execute('delete from luck_dingtalk_error')
        result = {
            "code": 1,
            "msg": "删除记录表数据成功"
        }
        return result

    # 删除记录表
    def drop_table(self):
        # 获取当前脚本的路径
        script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
        with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
            cursor.execute('drop table luck_dingtalk')
            cursor.execute('drop table luck_dingtalk_error')
        result = {
            "code": 1,
            "msg": "删除记录表成功"
        }
        return result

    # 通过钉钉群机器人发送群feedCard消息
    def send_feedcard_msg_to_group(self, links_list):
        # 发送群机器人消息时，下面的三个参数可以为空
        dingtalk_app_key = ""
        dingtalk_app_secret = ""
        dingtalk_agent_id = ""
        api = LuckDingtalkApi(dingtalk_app_key, dingtalk_app_secret, dingtalk_agent_id)
        dingtalk_robot_list = self.config["dingtalk_robot_list"]

        # 构造钉钉消息体
        msg = {
            "msgtype": "feedCard",
            "feedCard": {
                "links": json.dumps(links_list)
            }
        }

        check_id = int(time.time())
        check_user = "小程序"
        check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        check_environment = "prod"
        logging.info(
            f'{check_user} 于 {check_time} 通过钉钉群机器人发送群feedCard消息，dingtalk_robot_list：{dingtalk_robot_list}')
        result_data = []
        for dingtalk_robot in dingtalk_robot_list:
            dingtalk_robot_secret = dingtalk_robot["dingtalk_robot_secret"]
            dingtalk_robot_access_token = dingtalk_robot["dingtalk_robot_access_token"]
            check_item = dingtalk_robot_secret + " " + dingtalk_robot_access_token

            data = api.send_msg_by_robot(dingtalk_robot_secret, dingtalk_robot_access_token, msg)
            if data is not None:
                check_data = json.dumps(data)
                check_data = check_data.replace("'", '"')

                check_state = "正常"  # 正常/异常
                except_note = ""
                handle_state = ""  # 已处理/未处理
                # 获取当前脚本的路径
                script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
                with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                    insert_sql = f"insert into luck_dingtalk(id,check_user,check_time,check_environment,check_item,check_state,check_data,except_note,handle_state) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{check_state}','{check_data}','{except_note}','{handle_state}')"
                    cursor.execute(insert_sql)

                msg = f'通过钉钉群机器人发送群feedCard消息成功，dingtalk_robot：{dingtalk_robot}'
                logging.info(f'{msg}')
                result_data.append({
                    "code": 1,
                    "data": data,
                    "msg": f'{msg}'
                })
            else:
                # 添加错误日志
                msg = f'通过钉钉群机器人发送群feedCard消息异常，dingtalk_robot：{dingtalk_robot}'
                logging.error(msg)

                except_note = msg
                # 获取当前脚本的路径
                script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
                with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                    insert_sql = f"insert into luck_dingtalk_error(id,check_user,check_time,check_environment,check_item,except_note) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{except_note}')"
                    cursor.execute(insert_sql)

                result_data.append({
                    "code": 0,
                    "data": data,
                    "msg": f"{msg}"
                })

        return {
            "code": 1,
            "data": result_data,
            "msg": "通过钉钉群机器人发送群feedCard消息成功"
        }

    # 通过钉钉群机器人发送群链接消息
    def send_link_msg_to_group(self, link):
        # 发送群机器人消息时，下面的三个参数可以为空
        dingtalk_app_key = ""
        dingtalk_app_secret = ""
        dingtalk_agent_id = ""
        api = LuckDingtalkApi(dingtalk_app_key, dingtalk_app_secret, dingtalk_agent_id)
        dingtalk_robot_list = self.config["dingtalk_robot_list"]

        # 构造钉钉消息体
        msg = {
            "msgtype": "link",
            "link": link
        }

        check_id = int(time.time())
        check_user = "小程序"
        check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        check_environment = "prod"
        logging.info(
            f'{check_user} 于 {check_time} 通过钉钉群机器人发送群链接消息，dingtalk_robot_list：{dingtalk_robot_list}')
        result_data = []
        for dingtalk_robot in dingtalk_robot_list:
            dingtalk_robot_secret = dingtalk_robot["dingtalk_robot_secret"]
            dingtalk_robot_access_token = dingtalk_robot["dingtalk_robot_access_token"]
            check_item = dingtalk_robot_secret + " " + dingtalk_robot_access_token

            data = api.send_msg_by_robot(dingtalk_robot_secret, dingtalk_robot_access_token, msg)
            if data is not None:
                check_data = json.dumps(data)
                check_data = check_data.replace("'", '"')

                check_state = "正常"  # 正常/异常
                except_note = ""
                handle_state = ""  # 已处理/未处理
                # 获取当前脚本的路径
                script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
                with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                    insert_sql = f"insert into luck_dingtalk(id,check_user,check_time,check_environment,check_item,check_state,check_data,except_note,handle_state) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{check_state}','{check_data}','{except_note}','{handle_state}')"
                    cursor.execute(insert_sql)

                msg = f'通过钉钉群机器人发送群链接消息成功，dingtalk_robot：{dingtalk_robot}'
                logging.info(f'{msg}')
                result_data.append({
                    "code": 1,
                    "data": data,
                    "msg": f'{msg}'
                })
            else:
                # 添加错误日志
                msg = f'通过钉钉群机器人发送群消息链接异常，dingtalk_robot：{dingtalk_robot}'
                logging.error(msg)

                except_note = msg
                # 获取当前脚本的路径
                script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
                with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                    insert_sql = f"insert into luck_dingtalk_error(id,check_user,check_time,check_environment,check_item,except_note) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{except_note}')"
                    cursor.execute(insert_sql)

                result_data.append({
                    "code": 0,
                    "data": data,
                    "msg": f"{msg}"
                })

        return {
            "code": 1,
            "data": result_data,
            "msg": "通过钉钉群机器人发送群链接消息成功"
        }

    # 通过钉钉群机器人发送群文本消息
    def send_text_msg_to_group(self, text):
        # 发送群机器人消息时，下面的三个参数可以为空
        dingtalk_app_key = ""
        dingtalk_app_secret = ""
        dingtalk_agent_id = ""
        api = LuckDingtalkApi(dingtalk_app_key, dingtalk_app_secret, dingtalk_agent_id)
        dingtalk_robot_list = self.config["dingtalk_robot_list"]

        # 构造钉钉消息体
        msg = {
            "msgtype": "text",
            "text": text
        }

        check_id = int(time.time())
        check_user = "小程序"
        check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        check_environment = "prod"
        logging.info(
            f'{check_user} 于 {check_time} 通过钉钉群机器人发送群文本消息，dingtalk_robot_list：{dingtalk_robot_list}')
        result_data = []
        for dingtalk_robot in dingtalk_robot_list:
            dingtalk_robot_secret = dingtalk_robot["dingtalk_robot_secret"]
            dingtalk_robot_access_token = dingtalk_robot["dingtalk_robot_access_token"]
            check_item = dingtalk_robot_secret + " " + dingtalk_robot_access_token

            data = api.send_msg_by_robot(dingtalk_robot_secret, dingtalk_robot_access_token, msg)
            if data is not None:
                check_data = json.dumps(data)
                check_data = check_data.replace("'", '"')

                check_state = "正常"  # 正常/异常
                except_note = ""
                handle_state = ""  # 已处理/未处理
                # 获取当前脚本的路径
                script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
                with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                    insert_sql = f"insert into luck_dingtalk(id,check_user,check_time,check_environment,check_item,check_state,check_data,except_note,handle_state) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{check_state}','{check_data}','{except_note}','{handle_state}')"
                    cursor.execute(insert_sql)

                msg = f'通过钉钉群机器人发送群文本消息成功，dingtalk_robot：{dingtalk_robot}'
                logging.info(f'{msg}')
                result_data.append({
                    "code": 1,
                    "data": data,
                    "msg": f'{msg}'
                })
            else:
                # 添加错误日志
                msg = f'通过钉钉群机器人发送群消息文本异常，dingtalk_robot：{dingtalk_robot}'
                logging.error(msg)

                except_note = msg
                # 获取当前脚本的路径
                script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
                with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                    insert_sql = f"insert into luck_dingtalk_error(id,check_user,check_time,check_environment,check_item,except_note) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{except_note}')"
                    cursor.execute(insert_sql)

                result_data.append({
                    "code": 0,
                    "data": data,
                    "msg": f"{msg}"
                })

        return {
            "code": 1,
            "data": result_data,
            "msg": "通过钉钉群机器人发送群文本消息成功"
        }

    # 发送个人钉钉actionCard消息
    def send_actioncard_msg_to_person(self, action_card, userid_list):
        dingtalk_app_key = self.config["dingtalk_app_key"]
        dingtalk_app_secret = self.config["dingtalk_app_secret"]
        dingtalk_agent_id = self.config["dingtalk_agent_id"]
        api = LuckDingtalkApi(dingtalk_app_key, dingtalk_app_secret, dingtalk_agent_id)

        # 构造钉钉消息体
        msg = {
            "to_all_user": 'false',
            "agent_id": dingtalk_agent_id,
            "userid_list": userid_list,
            "msg": str({
                "msgtype": "action_card",
                "action_card": action_card
            }),
        }

        check_id = int(time.time())
        check_user = "小程序"
        check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        check_environment = "prod"
        logging.info(
            f'{check_user} 于 {check_time} 发送个人钉钉actionCard消息，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}')

        check_item = dingtalk_agent_id
        data = api.send_msg_to_person(msg)
        if data is not None:
            check_data = json.dumps(data)
            check_data = check_data.replace("'", '"')

            check_state = "正常"  # 正常/异常
            except_note = ""
            handle_state = ""  # 已处理/未处理
            # 获取当前脚本的路径
            script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
            with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                insert_sql = f"insert into luck_dingtalk(id,check_user,check_time,check_environment,check_item,check_state,check_data,except_note,handle_state) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{check_state}','{check_data}','{except_note}','{handle_state}')"
                cursor.execute(insert_sql)

            msg = f'发送个人钉钉actionCard消息成功，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}'
            logging.info(f'{msg}')
            return {
                "code": 1,
                "data": data,
                "msg": f'{msg}'
            }
        else:
            # 添加错误日志
            msg = f'发送个人钉钉actionCard消息异常，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}'
            logging.error(msg)

            except_note = msg
            # 获取当前脚本的路径
            script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
            with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                insert_sql = f"insert into luck_dingtalk_error(id,check_user,check_time,check_environment,check_item,except_note) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{except_note}')"
                cursor.execute(insert_sql)

            return {
                "code": 0,
                "data": data,
                "msg": f"{msg}"
            }

    # 发送个人钉钉链接消息
    def send_link_msg_to_person(self, link, userid_list):
        dingtalk_app_key = self.config["dingtalk_app_key"]
        dingtalk_app_secret = self.config["dingtalk_app_secret"]
        dingtalk_agent_id = self.config["dingtalk_agent_id"]
        api = LuckDingtalkApi(dingtalk_app_key, dingtalk_app_secret, dingtalk_agent_id)

        # 构造钉钉消息体
        msg = {
            "to_all_user": 'false',
            "agent_id": dingtalk_agent_id,
            "userid_list": userid_list,
            "msg": str({
                "msgtype": "link",
                "link": link
            }),
        }

        check_id = int(time.time())
        check_user = "小程序"
        check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        check_environment = "prod"
        logging.info(
            f'{check_user} 于 {check_time} 发送个人钉钉链接消息，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}')

        check_item = dingtalk_agent_id
        data = api.send_msg_to_person(msg)
        if data is not None:
            check_data = json.dumps(data)
            check_data = check_data.replace("'", '"')

            check_state = "正常"  # 正常/异常
            except_note = ""
            handle_state = ""  # 已处理/未处理
            # 获取当前脚本的路径
            script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
            with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                insert_sql = f"insert into luck_dingtalk(id,check_user,check_time,check_environment,check_item,check_state,check_data,except_note,handle_state) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{check_state}','{check_data}','{except_note}','{handle_state}')"
                cursor.execute(insert_sql)

            msg = f'发送个人钉钉链接消息成功，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}'
            logging.info(f'{msg}')
            return {
                "code": 1,
                "data": data,
                "msg": f'{msg}'
            }
        else:
            # 添加错误日志
            msg = f'发送个人钉钉链接消息异常，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}'
            logging.error(msg)

            except_note = msg
            # 获取当前脚本的路径
            script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
            with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                insert_sql = f"insert into luck_dingtalk_error(id,check_user,check_time,check_environment,check_item,except_note) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{except_note}')"
                cursor.execute(insert_sql)

            return {
                "code": 0,
                "data": data,
                "msg": f"{msg}"
            }

    # 发送个人钉钉文本消息
    def send_text_msg_to_person(self, content, userid_list):
        dingtalk_app_key = self.config["dingtalk_app_key"]
        dingtalk_app_secret = self.config["dingtalk_app_secret"]
        dingtalk_agent_id = self.config["dingtalk_agent_id"]
        api = LuckDingtalkApi(dingtalk_app_key, dingtalk_app_secret, dingtalk_agent_id)

        # 构造钉钉消息体
        msg = {
            "to_all_user": 'false',
            "agent_id": dingtalk_agent_id,
            "userid_list": userid_list,
            "msg": str({
                "msgtype": "text",
                "text": content
            }),
        }

        check_id = int(time.time())
        check_user = "小程序"
        check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        check_environment = "prod"
        logging.info(
            f'{check_user} 于 {check_time} 发送个人文本链接消息，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}')

        check_item = dingtalk_agent_id
        data = api.send_msg_to_person(msg)
        if data is not None:
            check_data = json.dumps(data)
            check_data = check_data.replace("'", '"')

            check_state = "正常"  # 正常/异常
            except_note = ""
            handle_state = ""  # 已处理/未处理
            # 获取当前脚本的路径
            script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
            with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                insert_sql = f"insert into luck_dingtalk(id,check_user,check_time,check_environment,check_item,check_state,check_data,except_note,handle_state) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{check_state}','{check_data}','{except_note}','{handle_state}')"
                cursor.execute(insert_sql)

            msg = f'发送个人钉钉文本消息成功，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}'
            logging.info(f'{msg}')
            return {
                "code": 1,
                "data": data,
                "msg": f'{msg}'
            }
        else:
            # 添加错误日志
            msg = f'发送个人钉钉文本消息异常，dingtalk_agent_id：{dingtalk_agent_id}，userid_list：{userid_list}'
            logging.error(msg)

            except_note = msg
            # 获取当前脚本的路径
            script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app
            with LuckSqliteHelperUtils(os.path.join(script_dir, 'works/', LuckDingtalkConstant.DB_NAME)) as cursor:
                insert_sql = f"insert into luck_dingtalk_error(id,check_user,check_time,check_environment,check_item,except_note) values ('{check_id}','{check_user}','{check_time}','{check_environment}','{check_item}','{except_note}')"
                cursor.execute(insert_sql)

            return {
                "code": 0,
                "data": data,
                "msg": f"{msg}"
            }
